<!--
 * @Description: ***
 * @Version: 1.0.0
 * @Autor: Caoyingwen
 * @Date: 2022-01-05 17:42:27
 * @LastEditors: Caoyingwen
 * @LastEditTime: 2022-01-05 18:08:14
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>demo01</title>
  <script src="./js/WebGL-compatibility-check.js"></script>
</head>
<body>
  <div id="container"></div>
  <script>
    if (WebGL.isWebGLAvailable()) {
    // Initiate function or other initializations here
      animate();
    } else {
      const warning = WebGL.getWebGLErrorMessage();
      document.getElementById('container').appendChild(warning);
    }
  </script>
  <!--canvas标签创建一个宽高均为500像素，背景为蓝色的矩形画布-->
<canvas id="webgl" width="500" height="500" style="background-color: blue"></canvas>

<!-- 顶点着色器源码 -->
<script id="vertexShader" type="x-shader/x-vertex">
  void main() {
    //给内置变量gl_PointSize赋值像素大小
    gl_PointSize=30.0;
    //顶点位置，位于坐标原点
    gl_Position =vec4(0.5,0.5,0.5,1.0);
  }
</script>
<!-- 片元着色器源码 -->
<script id="fragmentShader" type="x-shader/x-fragment">
  void main() {
    gl_FragColor = vec4(1.0,2.0,0.0,1.0);
  }
</script>

<script>
  //通过getElementById()方法获取canvas画布对象
var canvas= document.getElementById('webgl')
// 获得webgl上下文
var gl=canvas.getContext('webgl');

//顶点着色器源码
var vertexShaderSource = '' +
    'void main(){' +
    //给内置变量gl_PointSize赋值像素大小
    '   gl_PointSize=20.0;' +
    //顶点位置，位于坐标原点
    '   gl_Position =vec4(0.5,0.5,0.5,1.0);' +
    '}';

//片元着色器源码
var fragShaderSource = '' +
    'void main(){' +
    //定义片元颜色
    '   gl_FragColor = vec4(1.0,0.0,0.0,1.0);' +
    '}';

//声明初始化着色器函数
function initShader(gl,vertexShaderSource,fragmentShaderSource){
    //创建顶点着色器对象
    var vertexShader = gl.createShader(gl.VERTEX_SHADER);
    //创建片元着色器对象
    var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    //引入顶点、片元着色器源代码
    gl.shaderSource(vertexShader,vertexShaderSource);
    gl.shaderSource(fragmentShader,fragmentShaderSource);
    //编译顶点、片元着色器
    gl.compileShader(vertexShader);
    gl.compileShader(fragmentShader);

    //创建程序对象program
    var program = gl.createProgram();
    //附着顶点着色器和片元着色器到program
    gl.attachShader(program,vertexShader);
    gl.attachShader(program,fragmentShader);
    //链接program
    gl.linkProgram(program);
    //使用program
    gl.useProgram(program);
    //返回程序program对象
    return program;
}

// initShader(gl,vertexShaderSource,fragShaderSource)

//顶点着色器源码
var vertexShaderSource = document.getElementById('vertexShader').innerText;
//片元着色器源码
var fragShaderSource = document.getElementById('fragmentShader').innerText;
//初始化着色器
var program = initShader(gl,vertexShaderSource,fragShaderSource);

// 绘制显示结果
gl.drawArrays(gl.POINTS,0,1);

</script>
</body>
</html>